package com.yangjiayu.service.impl;

import com.yangjiayu.service.DocumentService;
import com.yangjiayu.utils.CustomTextSpliter;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Classname DocumentService
 * @Description TODO
 * @Date 2025/8/14 19:48
 * @Created by YangJiaYu
 */
@Service
@RequiredArgsConstructor
public class DocumentServiceImpl implements DocumentService {

    private final RedisVectorStore redisVectorStore;

    @Override
    public List<Document> loadText(Resource resource, String fileName) {
        // 加载读取文档
        TextReader textReader = new TextReader(resource);
        textReader.getCustomMetadata().put("fileName",fileName);
        List<Document>documentList = textReader.get();

//        System.out.println("document: " + documentList);


        // 默认的文本切分器 但是默认的切的chunk太大 跟没有切一样
//        TokenTextSplitter tokenTextSplitter = new TokenTextSplitter();
//        List<Document> list= tokenTextSplitter.apply(documentList);

        // 切分文档
        CustomTextSpliter tokenTextSplitter = new CustomTextSpliter();
        List<Document> list= tokenTextSplitter.apply(documentList);
        System.out.println("list = " + list);

        // 向量存储
        redisVectorStore.add(list);
        return  documentList;
    }

    @Override
    public List<Document> doSearch(String question) {

        return redisVectorStore.similaritySearch(question);
    }
}






